<template>
  <div id="app">
    <router-view />
    <van-tabbar v-model="active" fixed>
      <van-tabbar-item replace to="/cards" icon="home-o">健身会员</van-tabbar-item>
      <van-tabbar-item replace to="/user" icon="setting-o">个人中心</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue';
  import { useAppStore } from '@/store/modules/app';
  import { useCache, tokenKey } from '@/hooks/web/useCache';
  import { code2accesstokenApi, openid2tokenApi, getHotelInfoApi } from '@/api/wechat';
  import { getOpenId } from '@/utils';
  import { useRoute, useRouter } from 'vue-router'

  const { wsCache } = useCache()
  const { push } = useRouter()
  const appStore = useAppStore()
  const active = computed({
    get: () => appStore.getTabbarIndex,
    set: (value) => appStore.setTabbarIndex(value)
  })

  const getHotelInfo = async () => {
    await getHotelInfoApi()
    .then(res => {
      appStore.setHotelName(res.data.hotel_name)
      appStore.setAppId(res.data.appid)
      appStore.setImages(res.data.images)
      appStore.setMyImage(res.data.my_image)
    })
    .catch()
  }

  const login = async () => {
    if (!appStore.getAppId) {
      await getHotelInfo()
    }

    const openid = getOpenId()
    if (openid) {
      // 获取token
      const res = await openid2tokenApi()
      console.log(res)
      if (res) {
        wsCache.set(tokenKey, res.data.token)
        appStore.setOpenId(res.data.openid)
        appStore.setMobile(res.data.mobile || '')
        appStore.setGuestTitle(res.data.guest_title)
        appStore.setLastName(res.data.last_name)
      }
    } else { // 跳转code页面
      location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appStore.getAppId}&redirect_uri=${encodeURIComponent(location.origin)}&response_type=code&scope=snsapi_base#wechat_redirect`
    }
  }

  onMounted(async () => {
    const route = useRoute()

    if (route.query.code) {
      const res = await code2accesstokenApi({ code: route.query.code })
      console.log(res)
      wsCache.set(tokenKey, res.data.token)
      appStore.setOpenId(res.data.openid)
      // appStore.setMobile(res.data.mobile)
      await login()
      push('/')
    } else {
      await login()
    }
  })

</script>

<style lang="scss">
body {
  font-size: 16px;
  background-color: #f8f8f8;
  -webkit-font-smoothing: antialiased;

  .card-box+.card-box {
    margin-top: 18px;
  }
}
</style>
